import { FC, MutableRefObject, useEffect, useState } from 'react';
import FieldItem, { FieldItemProps } from './FieldItem';
import { IFormLayoutProps } from '@formily/antd/esm/form-layout';
import { Form } from 'antd';
import styles from './index.less';

interface FieldFormProps {
  formItemsRef: MutableRefObject<any>;
  layout?: IFormLayoutProps['layout'];
  fields?: FieldItemProps[];
  initialValues?: any;
}

const FieldForm: FC<FieldFormProps> = (props) => {
  const { fields, initialValues, formItemsRef } = props;
  const [form] = Form.useForm();

  useEffect(() => {
    form.setFieldsValue(initialValues);
  }, [initialValues]);

  return (
    <Form
      form={form}
      initialValues={initialValues}
      colon={false}
      labelCol={{ span: 8 }}
      labelAlign="left"
      onValuesChange={(value, allValues) => {
        let name;
        for (var member in value) {
          name = member
        }
        let suffix = allValues?.[name]?.[name === 'width' ? 'widthSuffix' : 'heightSuffix']
        if (suffix == '%') {
          const oldNumber = form.getFieldValue()?.[name]?.[name === 'width' ? 'widowWidth' : 'windowHeight'];
          const number = [30, 60, 90].includes(oldNumber) ? oldNumber : 60
          form.setFieldsValue({
            [name]: {
              [name === 'width' ? 'widthSuffix' : 'heightSuffix']: allValues[name]?.[name === 'width' ? 'widthSuffix' : 'heightSuffix'],
              [name === 'width' ? 'widowWidth' : 'windowHeight']: number
            },
          });
        }
        const newValue = form.getFieldsValue()
        formItemsRef.current.formItems = {
          ...allValues,
          ...newValue
        };
      }}
      className={styles['tag-form']}
    >
      {fields?.map((field) => (
        <FieldItem key={field.name} {...field} formValue={form} values={initialValues} />
      ))}
    </Form>
  );
};

export default FieldForm;
